﻿using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Electrical;
using Autodesk.Revit.UI;
using ControlzEx;
using MaterialDesignColors;
using MaterialDesignColors.ColorManipulation;
using MaterialDesignThemes.Wpf;
using Microsoft.Office.Interop.Excel;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using ZhuXingFamilys.ExportExcel;
using ZhuXingFamilys.ExportExcel.utils;
using ZhuXingFamilys.ModelInformation.Entity;
using Color = Autodesk.Revit.DB.Color;
using Parameter = Autodesk.Revit.DB.Parameter;
using TextBox = System.Windows.Controls.TextBox;

namespace ZhuXingFamilys.ModelInformation
{
    /// <summary>
    /// ModelInformationWindow.xaml 的交互逻辑
    /// </summary>
    public partial class ModelInformationWindow : System.Windows.Window
    {
        private static ModelInformationWindow staticInstance = null;
        private UIApplication uiApp;
        public ModelInformationWindow(UIApplication UIApp)
        {
            this.uiApp = UIApp;
            //ui库使用
            ColorZoneAssist.SetMode(new System.Windows.Controls.GroupBox(), ColorZoneMode.Light);
            Hue hue = new Hue("name", System.Windows.Media.Color.FromArgb(1, 2, 3, 4), System.Windows.Media.Color.FromArgb(1, 5, 6, 7));

            InitializeComponent();
        }
        // 窗口关闭
        private void Window_Closed(object sender, EventArgs e)
        {
            staticInstance = null;
        }
        // 获取实例
        internal static ModelInformationWindow GetInstance(UIApplication uiapp)
        {
            if (staticInstance == null)
            {
                staticInstance = new ModelInformationWindow(uiapp);
            }

            return staticInstance;
        }
        // 窗口加载完成
        private void ModelInformationWindow_OnLoaded(object sender, RoutedEventArgs e)
        {
            // 项目信息
            getProjectInfoList();
            // 建筑信息
            BuildingListBox.ItemsSource = GetBuildings();
        }

        // 获取链接中的建筑
        private List<ListBoxItem> GetBuildings()
        {
            // 创建一个空的 ListBoxItem 列表 ListListBoxItem
            List<ListBoxItem> ListListBoxItem = new List<ListBoxItem>();

            // 链接中的数据
            // 获取当前活动的 Revit 文档对象 doc。
            Document doc = uiApp.ActiveUIDocument.Document;
            
            // 创建一个过滤器对象 collector，用于收集文档中的元素。
            FilteredElementCollector collector = new FilteredElementCollector(doc);
           
            // 创建一个元素类过滤器 LinkFilter，过滤出 Revit 链接实例元素。
            ElementClassFilter LinkFilter = new ElementClassFilter(typeof(RevitLinkInstance));
           
            // 获取通过 LinkFilter 过滤后的元素迭代器 linkIterator。
            FilteredElementIterator linkIterator = collector.WherePasses(LinkFilter).GetElementIterator();
            
            // 进入 while 循环，迭代 linkIterator。
            while (linkIterator.MoveNext())
            {
                // 将当前元素 linkIterator.Current 转换为 Revit 链接实例对象 LinkInstance。
                RevitLinkInstance LinkInstance = linkIterator.Current as RevitLinkInstance;
                
                // 获取链接文档对象 LinkDoc。
                Document LinkDoc = LinkInstance.GetLinkDocument();
               
                // 如果 LinkDoc 不为空，则执行以下:
                if (LinkDoc != null)
                {
                    // 创建一个 ListBoxItem 对象 listBoxItem。
                    ListBoxItem listBoxItem = new ListBoxItem();
                    
                    // 设置 listBoxItem 的高度、宽度、边距和对齐方式。
                    listBoxItem.Height = 200;
                    listBoxItem.Width = 200;
                    listBoxItem.Margin = new Thickness(5);
                    listBoxItem.HorizontalContentAlignment = HorizontalAlignment.Center;
                    listBoxItem.HorizontalAlignment = HorizontalAlignment.Center;
                    
                    // 创建一个 StackPanel 对象 sp。
                    StackPanel sp = new StackPanel();

                    // 创建一个 Image 对象 image。
                    // Image image = new Image();

                    // 设置 image 的路径为 “./ IMG / 楼栋.JPG”。
                    // string imagePath = "./IMG/楼栋.JPG";
                    //string imagePath = "pack://application:,,,/ZhuXingFamilys;component/ModelInformation/IMG/楼栋.JPG";
                    //image.Source = new BitmapImage(new Uri(imagePath, UriKind.RelativeOrAbsolute));

                    string imagePath = "./IMG/工程项目信息.png";
                    Image image = new Image();
                    image.Source = new BitmapImage(new Uri(imagePath, UriKind.RelativeOrAbsolute));


                    //// 创建一个 Label 对象 label。
                    //Label label = new Label();

                    //// 获取链接文档的 ProjectInfo 对象 linkProjectInfo。
                    //ProjectInfo linkProjectInfo = LinkDoc.ProjectInformation;

                    //// 设置 label 的内容为 linkProjectInfo 的建筑名称。
                    //// label.Content = linkProjectInfo.Name;

                    //label.Content = LinkInstance.Name;
                    //label.TextWrapping = TextWrapping.Wrap;



                    //// 设置 label 的对齐方式和边距。
                    //label.HorizontalAlignment = HorizontalAlignment.Center;
                    //label.VerticalAlignment = VerticalAlignment.Center;
                    //label.Margin = new Thickness(5);

                    // 创建一个 TextBlock 对象 textBlock。
                    TextBlock textBlock = new TextBlock();
                    textBlock.Text = LinkInstance.Name;
                    textBlock.Text = LinkInstance.Name.Split('.')[0]; // 只取第一个值
                    textBlock.TextWrapping = TextWrapping.Wrap;

                    // 设置 textBlock 的对齐方式和边距。
                    textBlock.HorizontalAlignment = HorizontalAlignment.Center;
                    textBlock.VerticalAlignment = VerticalAlignment.Center;
                    textBlock.Margin = new Thickness(5);

                    // 将 image 和 label 添加到 sp 中。
                    sp.Children.Add(image);
                    sp.Children.Add(textBlock);
                    
                    // 将 sp 设置为 listBoxItem 的内容。
                    listBoxItem.Content = sp;
                    
                    // 建筑点击事件
                    // 添加建筑物点击事件处理程序，当用户点击 listBoxItem 时会执行相应的操作。
                    listBoxItem.MouseUp += (object sender, MouseButtonEventArgs e) =>
                    {
                        // MessageBox.Show(linkProjectInfo.BuildingName);
                        // 打开建筑信息窗口
                        BuildingInfo buildingInfo = new BuildingInfo(LinkDoc);
                        buildingInfo.Show();
                        buildingInfo.Activate();
                        if (buildingInfo.WindowState != WindowState.Normal)
                        {
                            buildingInfo.WindowState = WindowState.Normal;
                        }
                    };

                    // 将 listBoxItem 添加到 ListListBoxItem 列表中。
                    ListListBoxItem.Add(listBoxItem);
                }
            }
            
            // 循环结束后，返回 ListListBoxItem 列表。
            return ListListBoxItem;
        }

        // 获取项目信息
        private void getProjectInfoList()
        {
            Document doc = uiApp.ActiveUIDocument.Document;
            ProjectInfo proj = doc.ProjectInformation;
            ParameterSet projParameters = proj.Parameters;

            var basicXTextBox = ProjectInfoWP.Children.OfType<TextBox>().FirstOrDefault(tb => tb.Name == "基点坐标X");
            var basicYTextBox = ProjectInfoWP.Children.OfType<TextBox>().FirstOrDefault(tb => tb.Name == "基点坐标Y");
            var basicZTextBox = ProjectInfoWP.Children.OfType<TextBox>().FirstOrDefault(tb => tb.Name == "基点坐标Z");
            var AngleTextBox = ProjectInfoWP.Children.OfType<TextBox>().FirstOrDefault(tb => tb.Name == "旋转角度");

            // MessageBox.Show($"{basicZTextBox.Name},{basicZTextBox.Text}");

            var x = "";
            var y = "";
            var z = "";
            var angle = 0.0;

            var collector = new FilteredElementCollector(doc);
            collector.OfCategory(BuiltInCategory.OST_ProjectBasePoint).OfClass(typeof(BasePoint));
            foreach (Element elem in collector.ToElements())
            {
                x = elem.LookupParameter("北/南").AsValueString();
                y = elem.LookupParameter("东/西").AsValueString();
                z = elem.LookupParameter("高程").AsValueString();
                angle = elem.LookupParameter("到正北的角度").AsDouble();
            }

            var children = ProjectInfoWP.Children;

            foreach (Parameter projParameter in projParameters)
            {
                foreach (var child in children)
                {
                    if (child is TextBox)
                    {
                        var tb = child as TextBox;
                        if (projParameter.Definition.Name.Equals(tb.Name))
                        {
                            tb.Text = projParameter.AsString();

                            string selectedText = projParameter.AsValueString();
                            if (selectedText == null)
                            {
                                basicXTextBox.Text = x;
                                basicYTextBox.Text = y;
                                basicZTextBox.Text = z;
                                string text1 = angle.ToString();
                                AngleTextBox.Text = text1;
                            }
                            else
                            {
                                tb.SelectedText = selectedText;
                            }
                        }

                        
                    }
                }
            }




            var TeXTextBox = ProjectInfoWP.Children.OfType<TextBox>().FirstOrDefault(tb => tb.Name == "项目特征点坐标X");
            var TeYTextBox = ProjectInfoWP.Children.OfType<TextBox>().FirstOrDefault(tb => tb.Name == "项目特征点坐标Y");
            var TeZTextBox = ProjectInfoWP.Children.OfType<TextBox>().FirstOrDefault(tb => tb.Name == "项目特征点坐标Z");
            

            var Tex = "";
            var Tey = "";
            var Tez = "";
            

            var collector1 = new FilteredElementCollector(doc);
            collector1.OfCategory(BuiltInCategory.OST_SharedBasePoint).OfClass(typeof(BasePoint));
            foreach (Element elem in collector1.ToElements())
            {
                Tex = elem.LookupParameter("北/南").AsValueString();
                Tey = elem.LookupParameter("东/西").AsValueString();
                Tez = elem.LookupParameter("高程").AsValueString();
                
            }

            var children1 = ProjectInfoWP.Children;

            foreach (Parameter projParameter in projParameters)
            {
                foreach (var child in children1)
                {
                    if (child is TextBox)
                    {
                        var tb = child as TextBox;
                        if (projParameter.Definition.Name.Equals(tb.Name))
                        {
                            tb.Text = projParameter.AsString();

                            string selectedText = projParameter.AsValueString();
                            if (selectedText == null)
                            {
                                TeXTextBox.Text = Tex;
                                TeYTextBox.Text = Tey;
                                TeZTextBox.Text = Tez;
                                
                            }
                            else
                            {
                                tb.SelectedText = selectedText;
                            }
                        }


                    }
                }
            }


        }
        // 总图信息
        private void zt_Button_Click(object sender, RoutedEventArgs e)
        {
            GeneralDrawingInfo instance = GeneralDrawingInfo.GetInstance(uiApp);
            if (instance.WindowState == WindowState.Minimized)
                instance.WindowState = WindowState.Normal;
            else
            {
                instance.Show();
                instance.Activate();
            }
        }

        private void 勘察单位_TextChanged(object sender, TextChangedEventArgs e)
        {

        }
        private void Composite(object sender, RoutedEventArgs e)
        {
            Document doc = uiApp.ActiveUIDocument.Document;
            var coll = new FilteredElementCollector(doc);

            foreach (RevitLinkInstance LinkInstance in coll.OfClass(typeof(RevitLinkInstance)).ToElements())
            {
                Document linkDoc = LinkInstance.GetLinkDocument();
                if (linkDoc == null)
                {
                    MessageBox.Show("linkDoc 为空 ");
                    continue;
                }

                ElementId targetViewId = new ElementId(96277); // 指定视图的Id
                View linkView = linkDoc.GetElement(targetViewId) as View;

                if (linkView == null)
                {
                    MessageBox.Show("linkView 为空 ");
                    continue;
                }

                var filterIds = linkView.GetFilters(); // 获取链接文档的过滤器
                if (filterIds == null)
                {
                    MessageBox.Show("filterIds 为空 ");
                    continue;
                }

                foreach (ElementId id in filterIds)
                {
                    ParameterFilterElement filter = linkDoc.GetElement(id) as ParameterFilterElement;
                    if (filter == null)
                        continue;

                    OverrideGraphicSettings ogs = linkView.GetFilterOverrides(id);
                    if (ogs != null && ogs.SurfaceBackgroundPatternColor.IsValid)
                    {
                        Color color = ogs.SurfaceBackgroundPatternColor;

                        if (filter.Name == "门" && (color.Red != 253 || color.Green != 157 || color.Blue != 11))
                        {
                            MessageBox.Show($"{filter.Name}的RGB: {color.Red},{color.Green},{color.Blue} 不等于给定的值 253,157,11");
                        }
                        else if (filter.Name == "墙" && (color.Red != 200 || color.Green != 204 || color.Blue != 201))
                        {
                            MessageBox.Show($"{filter.Name}的RGB: {color.Red},{color.Green},{color.Blue} 不合格");
                        }
                        else
                        {
                            MessageBox.Show($" 合格的有  模型的名称: {linkDoc.Title}  过滤器的名称: {filter.Name}  RGB: {color.Red},{color.Green},{color.Blue}");
                        }
                    }
                }
            }
        }

        private void wall(object sender, RoutedEventArgs e)
        {
            Document doc = uiApp.ActiveUIDocument.Document;

            var linkInstances = new FilteredElementCollector(doc)
                .OfClass(typeof(RevitLinkInstance))
                .ToElements()
                .Cast<RevitLinkInstance>();
            StringBuilder roomInfo = new StringBuilder();

            foreach (RevitLinkInstance linkInstance in linkInstances)
            {
                Document linkDoc = linkInstance.GetLinkDocument();
                if (linkDoc == null) continue;

                var walls = new FilteredElementCollector(linkDoc)
                    .OfCategory(BuiltInCategory.OST_Walls)
                    .WhereElementIsNotElementType()
                    .ToElements()
                    .Cast<Wall>();

                int compoundWallCount = 0; // 将此行代码移到内层循环之前


                foreach (Wall wallElement in walls)
                {
                    CompoundStructure compoundStructure = wallElement.WallType.GetCompoundStructure();
                    if (compoundStructure.LayerCount >= 2)
                    {
                        compoundWallCount++;

                        IList<CompoundStructureLayer> layers = compoundStructure.GetLayers();

                        foreach (CompoundStructureLayer layer in layers)
                        {
                            Material material = linkDoc.GetElement(layer.MaterialId) as Material;
                            // double thickness = layer.Width;
                            double thicknessFeet = layer.Width;  // 厚度（英尺）
                            double thicknessMeters = thicknessFeet * 0.3048 * 1000;  // 转换为毫米

                            roomInfo.AppendLine($"材质：{material?.Name}，厚度：{thicknessMeters}");
                        }
                        roomInfo.AppendLine("------------------------------"); // 添加分隔符
                    }
                }
                MessageBox.Show($"链接单体'{linkDoc.Title}'中的复合墙的数量为：{compoundWallCount} 总数:{walls.Count()}");
                TaskDialog.Show("信息", $"{roomInfo.ToString()}");
            }
        }

        private void pillar(object sender, RoutedEventArgs e)
        {
            Document doc = uiApp.ActiveUIDocument.Document;
            HashSet<string> displayedTypes = new HashSet<string>();
            Dictionary<string, HashSet<string>> linkTypeMap = new Dictionary<string, HashSet<string>>();
            StringBuilder result = new StringBuilder();
            var linkInstanceCollector = new FilteredElementCollector(doc).OfClass(typeof(RevitLinkInstance));

            foreach (RevitLinkInstance linkInstance in linkInstanceCollector)
            {
                Document linkDoc = linkInstance.GetLinkDocument();
                if (linkDoc == null) continue;
                result.AppendLine($"链接单体: {linkDoc.Title}");
                var columnCollector = new FilteredElementCollector(linkDoc).OfCategory(BuiltInCategory.OST_StructuralColumns);

                foreach (Element column in columnCollector)
                {
                    string typeName = "";
                    Parameter typeParam = column.LookupParameter("族与类型");

                    if (typeParam != null && typeParam.AsValueString() != null)
                    {
                        typeName = typeParam.AsValueString();
                    }

                    if (!string.IsNullOrEmpty(typeName) && column is FamilyInstance columnInstance)
                    {
                        ElementType elementType = linkDoc.GetElement(columnInstance.GetTypeId()) as ElementType;
                        if (elementType != null)
                        {
                            Parameter widthParam = elementType.LookupParameter("b");
                            Parameter heightParam = elementType.LookupParameter("h");
                            if (widthParam != null && heightParam != null)
                            {
                                double width = widthParam.AsDouble() * 0.3048 * 1000;
                                double height = heightParam.AsDouble() * 0.3048 * 1000;

                                if (!linkTypeMap.ContainsKey(linkDoc.Title))
                                {
                                    linkTypeMap.Add(linkDoc.Title, new HashSet<string>());
                                }

                                // 只有当类型名称未显示过时才显示信息
                                if (!displayedTypes.Contains(typeName) && !linkTypeMap[linkDoc.Title].Contains(typeName))
                                {
                                    displayedTypes.Add(typeName);
                                    linkTypeMap[linkDoc.Title].Add(typeName);

                                    result.AppendLine($"类型: {typeName}   b = {width}, h = {height}");
                                    result.AppendLine("------------------------------"); // 添加分隔符
                                }
                            }
                        }
                    }
                }
            }

            if (displayedTypes.Count == 0)
            {
                result.AppendLine("没有找到链接单体和类型的对应关系");
            }

            TaskDialog.Show("信息", $"{result.ToString()}");
        }
    }
}
                